#!/bin/python

# --------------------------------------
# VIDEO BUDDHA - database class
# --------------------------------------
# Ranames files based on a specific regex pattern in 
#  show_list.db and based on a specific list of file 
#  extensions.
# --------------------------------------

from sqlite3 import *
from sqlite3 import dbapi2 as sqlite

class Database:
	
	def __init__(self):
		# Establish a DB connection
		self.conn = connect('show_list.db')
		self.curs = self.conn.cursor()
		
		# Create the db if it doesn't exist
		self.createTables()
		
		self.insert_option('b_remember_dir', 1)
		self.insert_option('b_log', 0)
		self.insert_option('prev_dir', '')
		self.insert_option('seasep_format', 1)
		self.insert_option('b_keep_trailing', 0)
		self.insert_option('renaming_scheme', '%t - %se - %i')
		self.insert_option('video_extensions', '.avi .mpg .mp4 .mkv')		
		self.insert_option('b_write_nfo', 0)	
		self.insert_option('last_show', 'last_show_text')
		self.insert_option('last_show_id', '00000')
			
	def __del__(self):
		self.curs.close()
		self.conn.close()
		
	def close(self):
		self.__del__()
		
	def createTables(self):
		self.curs.execute("create table IF NOT EXISTS definitions (id integer primary key, old_name text, new_name text)")
		self.curs.execute("create table IF NOT EXISTS options (key text unique not null, val text)")
		self.conn.commit()
			
	def insert(self, oldName, newName):
		self.curs.execute("insert into definitions values (?, ?, ?)", (None, oldName, newName))
		self.conn.commit()
	
	def delete(self, id):
		self.curs.execute("delete from definitions where id = ?", id)
		self.conn.commit()
		
	def update(self, id, oldName, newName):
		self.curs.execute("update definitions set old_name = ?, new_name = ? where id = ?", (oldName, newName, id))
		self.conn.commit()
			
	def retrieve(self):
		data = self.curs.execute("select id, old_name, new_name from definitions")
		return data
		
	def retrieveId(self, id):
		data = self.curs.execute("select * from definitions where id = ?", [id])
		return data
	
	def insert_option(self, key, val):
		self.curs.execute("insert or ignore into options values (?, ?)", (key, val))
		self.conn.commit()
	
	def get_option(self, key):
		self.curs.execute("select key, val from options where key = ?", [key])
		data = self.curs.fetchone()
		return data
		
	def update_option(self, key, val):
		self.curs.execute("update options set val = ? where key = ?", (val, key))
		self.conn.commit()